package com.iv.durian.cloud.api;


import com.iv.durian.cloud.JsonResult;
import com.iv.durian.cloud.User;
import com.iv.durian.cloud.api.service.UserService;
import com.iv.durian.cloud.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
@Slf4j
@Api(value = "UserApi" ,description = "UserApi",tags={"user"} )
public class UserApi {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "获取用户信息")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<JsonResult<UserVO>> getUser (
            @RequestParam(value = "userId") Integer id){
        JsonResult r = new JsonResult();
        try {
            User user = userService.getUserById(id);
            if (user != null) {
                UserVO userVO = UserVO.builder()
                        .id(user.getId())
                        .email(user.getEmail())
                        .mobile(user.getMobile())
                        .status(user.getStatus())
                        .createTime(user.getCreateTime())
                        .updateTime(user.getUpdateTime()).build();
                r.ok(userVO);
            }
        } catch (Exception e) {
            r.error(e.getClass().getName() + ":" + e.getMessage());
            log.error("用户信息查询失败",e);
        }
        return ResponseEntity.ok(r);
    }



    @ApiOperation(value = "修改密码",notes = "http://xxxx.com/change/password?access_token=xxxxx")
    @RequestMapping(value = "/change/password", method = RequestMethod.POST)
    public void changePassword(
            @RequestParam(value = "userId") Integer userId,
            @ApiParam(name = "original_pwd",value = "原密码",required = true) @RequestParam(value = "original_pwd") String originalPwd,
            @ApiParam(name = "new_pwd",value = "新密码",required = true) @RequestParam(value = "new_pwd") String newPwd ){
        User user = userService.getUserById(userId);
        Assert.notNull(user,"用户不存在");
        Assert.isTrue(userService.verifyPassword(user,originalPwd),"原密码不正确");
        userService.updatePassword(user.getId(),newPwd);
    }

}
